package com.cnbm.wcsbasic.protocol.netty.modbus.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import com.cnbm.wcsbasic.protocol.netty.io.common.Package;
import com.cnbm.wcsbasic.protocol.netty.io.syn.SendedList;


/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2024-06-06 10:45
 */
public class ModbusTcpDecode extends LengthFieldBasedFrameDecoder {

    private static final int HEADER_SIZE = 6;
    //Constants
    private static final int MAX_FRAME_LENGTH = Integer.MAX_VALUE;
    private static final int LENGTH_FIELD_OFFSET = 0;
    private static final int LENGTH_FIELD_LENGTH = 4;
    private static final int LENGTH_FIELD_ADJUSTMENT = 0;
    private static final int INITIAL_BYTES_TO_STRIP = 4;
    private static final boolean FAIL_FAST = true;



    public ModbusTcpDecode() {
        super(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_FIELD_ADJUSTMENT, INITIAL_BYTES_TO_STRIP, FAIL_FAST);
    }



    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        if(in == null){
            return null;
        }
        if (in.readableBytes() < HEADER_SIZE){
            throw new Exception("readed bytes < header length");
        }


        //get 一个 4字节长度 的int
        int dataLength = in.getInt(2);
        //数据不正确，则抛出AioDecodeException异常
        if (dataLength < 0) {
            throw new Exception("bodyLength [" + dataLength + "] is not right, remote:" + ctx.channel().remoteAddress());
        }
        int neededLength = HEADER_SIZE + dataLength;

        //收到的数据是否足够组包

        int isDataEnough = in.readableBytes() - neededLength;


        if(isDataEnough<0){
            // 不够消息体长度(剩下的buffe组不了消息体),重新去组包
            return null;
        }else {
            //组包成功
            byte[] body = new byte[neededLength];
            in.readBytes(body);
            //System.out.println("received bytes :"+ Arrays.toString(body));
            String uuid = body[0]+"-"+body[1];
            Package mbPackage = new Package(body,uuid);
            SendedList.set(uuid , mbPackage);
        }
        return null;
    }
}
